package com.ccjk.beusoft.hot;

import android.content.Context;
import android.os.IBinder;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;

/**
 * Created by CCJK on 2017/12/5.
 */

public class BinderHookHelper {
    public static void hookClipboardService() {
        try {
            Class serviceManagerClass = Class.forName("android.os.ServiceManager");
            Method getServiceMethod = serviceManagerClass.getDeclaredMethod("getService", new Class[]{String.class});
            getServiceMethod.setAccessible(true);
            //拿到service原始的代理binder，
            IBinder clipboardService = (IBinder) getServiceMethod.invoke(null, Context.CLIPBOARD_SERVICE);

            //通过代理再次代理原始的binder
            IBinder prxoyService = (IBinder) Proxy.newProxyInstance(serviceManagerClass.getClassLoader(),
                    new Class[]{IBinder.class}, new HookServiceHandler(clipboardService));
            //替换ServiceManager中缓存表中的service的binder为我们代理的binder
            Field sCacheField=serviceManagerClass.getDeclaredField("sCache");
            sCacheField.setAccessible(true);
            HashMap<String, IBinder> sCache= (HashMap<String, IBinder>) sCacheField.get(null);
            sCache.put(Context.CLIPBOARD_SERVICE,prxoyService);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }

}
